package ewelinkapi

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/libs_2/ewelinkapi/constant"
	"gitee.com/libs_2/ewelinkapi/model"
)

// 获取设备操作历史
func (c *Client) GetOperationHistory(ctx context.Context, req model.DeviceOperationHistoryRequest) error {
	body, err := json.Marshal(req)
	if err != nil {
		return err
	}

	bs, err := c.doPost(ctx, constant.URL_DEVICE_HISTORY, false, true, false, body)
	if err != nil {
		return err
	}

	fmt.Printf("%v", string(bs))
	return nil
}

// 获取设备列表,limit 传30，offset 从0开始
//
// https://coolkit-carl.gitee.io/apidocs/#/zh-cmn/%E6%8E%A5%E5%8F%A3%E4%B8%AD%E5%BF%83_v2?id=%e8%8e%b7%e5%8f%96-thing-%e5%88%97%e8%a1%a8
func (c *Client) GetThings(ctx context.Context, limit, offset int) (model.ThingInfo, error) {
	bs, err := c.doGet(ctx, fmt.Sprintf(constant.URL_DEVICE_THING, limit, offset), false, true, false)
	if err != nil {
		return model.ThingInfo{}, err
	}

	fmt.Printf("%v", string(bs))
	var res model.ThingsResponse
	json.Unmarshal(bs, &res)
	if res.Code != 0 {
		return res.Data, fmt.Errorf("code:%d msg:%s", res.Code, res.Msg)
	}

	return res.Data, nil
}

// 删除设备
func (c *Client) DeleteDevice(ctx context.Context, deviceId string) error {
	bs, err := c.doDelete(ctx, fmt.Sprintf(constant.URL_DEVICE_DELETE, deviceId), true, true, false)
	if err != nil {
		return err
	}

	// fmt.Printf("%v", string(bs))
	var res model.CommonResponse
	json.Unmarshal(bs, &res)
	if res.Code != 0 {
		return fmt.Errorf("code:%d msg:%s", res.Code, res.Msg)
	}
	return nil
}
